<template>
  <div class="sleep-container">
    <!-- 主要内容区 -->
    <div class="main-content">
      <!-- 左侧：睡眠记录表单 -->
      <el-card class="record-form">
        <div slot="header">
          <span>记录睡眠</span>
        </div>
        <el-form :model="sleepForm" :rules="rules" ref="sleepForm" label-width="120px">
          <el-form-item label="睡眠日期" prop="date">
            <el-date-picker
              v-model="sleepForm.date"
              type="date"
              placeholder="选择日期"
              style="width: 100%">
            </el-date-picker>
          </el-form-item>
          
          <el-form-item label="入睡时间" prop="sleepTime">
            <el-time-picker
              v-model="sleepForm.sleepTime"
              placeholder="选择时间"
              format="HH:mm"
              style="width: 100%">
            </el-time-picker>
          </el-form-item>
          
          <el-form-item label="起床时间" prop="wakeTime">
            <el-time-picker
              v-model="sleepForm.wakeTime"
              placeholder="选择时间"
              format="HH:mm"
              style="width: 100%">
            </el-time-picker>
          </el-form-item>
          
          <el-form-item label="睡眠质量" prop="quality" class="quality-form-item">
            <el-rate
              v-model="sleepForm.quality"
              :colors="['#99A9BF', '#F7BA2A', '#FF9900']"
              :max="5">
            </el-rate>
          </el-form-item>
          
          <el-form-item label="睡眠感受" prop="feeling">
            <el-select v-model="sleepForm.feeling" placeholder="请选择" style="width: 100%">
              <el-option label="精力充沛" value="energetic"></el-option>
              <el-option label="一般" value="normal"></el-option>
              <el-option label="疲惫" value="tired"></el-option>
            </el-select>
          </el-form-item>
          
          <el-form-item label="备注" prop="note">
            <el-input
              type="textarea"
              v-model="sleepForm.note"
              :rows="3"
              placeholder="记录影响睡眠的因素，如：压力、饮食、运动等">
            </el-input>
          </el-form-item>
          
          <el-form-item>
            <el-button type="primary" @click="submitForm('sleepForm')" style="width: 100%">保存记录</el-button>
          </el-form-item>
        </el-form>
      </el-card>

      <!-- 右侧：数据分析 -->
      <div class="analysis-section">
        <!-- 时间范围选择 -->
        <el-card class="time-range">
          <el-radio-group v-model="timeRange" @change="handleTimeRangeChange">
            <el-radio-button label="day">今日</el-radio-button>
            <el-radio-button label="week">本周</el-radio-button>
            <el-radio-button label="month">本月</el-radio-button>
          </el-radio-group>
        </el-card>

        <!-- 睡眠数据统计 -->
        <el-card class="sleep-stats">
          <div slot="header">
            <span>睡眠统计</span>
          </div>
          <div class="stats-content">
            <div class="stat-item">
              <h3>{{ timeRange === 'day' ? '今日睡眠时长' : '平均睡眠时长' }}</h3>
              <div class="value-container">
                <p v-if="hasData" class="number">{{ averageSleepTime }}</p>
                <p v-else class="no-data">暂无记录</p>
                <p v-if="hasData" class="unit">小时</p>
              </div>
            </div>
            <div class="stat-item">
              <h3>{{ timeRange === 'day' ? '今日睡眠质量' : '平均睡眠质量' }}</h3>
              <div class="value-container">
                <p v-if="hasData" class="number">{{ averageQuality }}</p>
                <p v-else class="no-data">暂无记录</p>
                <p v-if="hasData" class="unit">分</p>
              </div>
            </div>
            <div class="stat-item">
              <h3>最佳睡眠时间</h3>
              <div class="value-container">
                <p v-if="hasData" class="number">{{ bestSleepTime }}</p>
                <p v-else class="no-data">暂无记录</p>
                <p v-if="hasData" class="unit">点</p>
              </div>
            </div>
          </div>
        </el-card>

        <!-- 图表区容器 -->
        <div class="charts-container" v-show="timeRange !== 'day'">
          <!-- 睡眠趋势图 -->
          <transition name="fade">
            <el-card class="sleep-trend" v-show="timeRange !== 'day'">
              <div slot="header">
                <span>睡眠趋势</span>
              </div>
              <div class="chart-container" ref="sleepChart">
                <!-- 添加加载提示 -->
                <div class="chart-loading" v-if="!sleepChart">
                  <i class="el-icon-loading"></i>
                  <p>加载中...</p>
                </div>
                <!-- 添加无数据提示 -->
                <div class="chart-empty" v-else-if="noChartData">
                  <i class="el-icon-data-analysis"></i>
                  <p>暂无睡眠趋势数据</p>
                </div>
              </div>
            </el-card>
          </transition>
        </div>

        <!-- 睡眠建议 -->
        <el-card class="sleep-advice">
          <div slot="header">
            <span>睡眠建议</span>
          </div>
          <div class="advice-content">
            <!-- 在日视图显示日建议 -->
            <div v-if="timeRange === 'day'" class="day-advice">
              <div v-if="dayAdvice" class="day-advice-content">
                <div class="formatted-advice" v-html="formatAdvice(dayAdvice)"></div>
              </div>
              <div v-else-if="!dayAdvice && hasData" class="loading-advice">
                <i class="el-icon-loading"></i>
                <p>加载日建议中...</p>
              </div>
              <div v-else class="no-data-advice">
                <!-- 当没有数据时显示默认建议 -->
                <el-collapse v-model="activeAdvice">
              <el-collapse-item title="作息建议" name="1">
                <div class="advice-item">
                  <i class="el-icon-time"></i>
                  <p>{{ advice.schedule }}</p>
                </div>
              </el-collapse-item>
              <el-collapse-item title="环境建议" name="2">
                <div class="advice-item">
                  <i class="el-icon-house"></i>
                  <p>{{ advice.environment }}</p>
                </div>
              </el-collapse-item>
              <el-collapse-item title="饮食建议" name="3">
                <div class="advice-item">
                  <i class="el-icon-food"></i>
                  <p>{{ advice.diet }}</p>
                </div>
              </el-collapse-item>
            </el-collapse>
              </div>
            </div>
            
            <!-- 在周视图显示周建议 -->
            <div v-if="timeRange === 'week'" class="week-advice">
              <div v-if="weekAdvice" class="week-advice-content">
                <div class="formatted-advice" v-html="formatAdvice(weekAdvice)"></div>
              </div>
              <div v-else class="loading-advice">
                <i class="el-icon-loading"></i>
                <p>加载周建议中...</p>
              </div>
            </div>
            
            <!-- 在月视图显示月度建议 -->
            <div v-if="timeRange === 'month'" class="month-advice">
              <div v-if="monthAdvice" class="month-advice-content">
                <div class="formatted-advice" v-html="formatAdvice(monthAdvice)"></div>
              </div>
              <div v-else class="loading-advice">
                <i class="el-icon-loading"></i>
                <p>加载月度建议中...</p>
              </div>
            </div>
          </div>
        </el-card>
      </div>
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts'

export default {
  name: 'SleepView',
  data() {
    return {
      sleepForm: {
        date: new Date(),
        sleepTime: null,
        wakeTime: null,
        quality: 3,
        feeling: '',
        note: ''
      },
      rules: {
        date: [{ required: true, message: '请选择日期', trigger: 'change' }],
        sleepTime: [{ required: true, message: '请选择入睡时间', trigger: 'change' }],
        wakeTime: [{ required: true, message: '请选择起床时间', trigger: 'change' }],
        quality: [{ required: true, message: '请评价睡眠质量', trigger: 'change' }],
        feeling: [{ required: true, message: '请选择睡眠感受', trigger: 'change' }]
      },
      timeRange: 'day',
      averageSleepTime: '--',
      averageQuality: '--',
      bestSleepTime: '--',
      activeAdvice: ['1'],
      advice: {
        schedule: '建议您保持规律的作息时间，每天在23:00前入睡，确保7-8小时的睡眠时间。',
        environment: '保持卧室安静、黑暗和凉爽，温度控制在18-22℃之间，使用遮光窗帘和耳塞。',
        diet: '睡前2-3小时避免进食，特别是咖啡因和酒精。可以喝一杯温牛奶帮助入睡。'
      },
      monthAdvice: '',
      weekAdvice: '',
      dayAdvice: '',
      sleepChart: null,
      noChartData: false,
      hasData: false
    }
  },
  mounted() {
    // 添加窗口大小变化监听，以便调整图表大小
    window.addEventListener('resize', this.handleResize);
    
    // 在初始化时如果不是"今日"视图，预先创建图表容器
    this.$nextTick(() => {
      if (this.timeRange !== 'day') {
        this.initChart();
      }
      
      // 加载睡眠数据
      this.loadSleepData();
    });
  },
  watch: {
    timeRange(newVal, oldVal) {
      // 当时间范围变化时
      this.$nextTick(() => {
        if (newVal !== 'day') {
          // 确保DOM已更新
          setTimeout(() => {
            if (!this.sleepChart) {
              this.initChart();
            } else {
              this.sleepChart.resize();
            }
            
            // 根据选择的时间范围加载数据
            if (newVal === 'week') {
              this.loadWeekSleepData();
              // 加载周睡眠建议
              this.loadWeekSleepAdvice();
            } else if (newVal === 'month') {
              this.loadMonthSleepData();
              // 加载月度睡眠建议
              this.loadMonthSleepAdvice();
            }
          }, 50);
        }
      });
    }
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // 准备发送到后端的数据
          const sleepData = {
            sleepDate: this.formatDateForBackend(this.sleepForm.date),
            sleepTime: this.formatTimeForBackend(this.sleepForm.sleepTime),
            wakeTime: this.formatTimeForBackend(this.sleepForm.wakeTime),
            sleepQuality: this.sleepForm.quality,
            sleepFeeling: this.sleepForm.feeling,
            remark: this.sleepForm.note
          };
          
          // 调用API保存睡眠记录
          this.axios.post('/api/userSleep/save', sleepData)
            .then(response => {
              if (response.data === "睡眠记录保存成功") {
                this.$message.success('睡眠记录保存成功！');
                this.resetForm(formName);
                // 保存成功后更新数据
                this.loadSleepData();
        } else {
                this.$message.error(response.data || '保存失败，请稍后重试');
              }
            })
            .catch(error => {
              console.error('保存睡眠记录失败:', error);
              this.$message.error('保存失败，请稍后重试');
            });
        } else {
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
    },
    handleTimeRangeChange(value) {
      // 切换视图后，确保图表正确初始化或更新
      this.$nextTick(() => {
        if (value !== 'day') {
          // 给DOM更新留出时间
          setTimeout(() => {
            if (!this.sleepChart) {
              this.initChart();
            } else {
              this.sleepChart.resize();
            }
            
            // 根据选择的时间范围加载数据
            if (value === 'week') {
              this.loadWeekSleepData();
              // 加载周睡眠建议
              this.loadWeekSleepAdvice();
            } else if (value === 'month') {
              this.loadMonthSleepData();
              // 加载月度睡眠建议
              this.loadMonthSleepAdvice();
            }
          }, 50);
        } else {
          // 如果切换到"今日"视图，加载今日数据
          this.loadTodaySleepData();
          // 加载日睡眠建议
          this.loadDaySleepAdvice();
        }
      });
    },
    handleResize() {
      // 调整图表大小
      if (this.sleepChart) {
        this.sleepChart.resize();
      }
    },
    initChart() {
      // 确保DOM元素存在再初始化
      if (!this.$refs.sleepChart) {
        console.log('Sleep chart container not found');
        return;
      }
      
      // 如果已经有实例，先销毁
      if (this.sleepChart) {
        this.sleepChart.dispose();
        this.sleepChart = null;
      }
      
      try {
        // 初始化echarts
        this.sleepChart = echarts.init(this.$refs.sleepChart);
        // 不再调用updateChart，而是等待数据加载后再更新图表
      } catch (error) {
        console.error('Failed to initialize sleep chart:', error);
      }
    },
    updateChartWithData(xAxisData, sleepTimeData, qualityData) {
      if (!this.sleepChart) return
      
      // 手动计算平均值，确保睡眠质量在0-5之间
      const avgSleepTime = sleepTimeData.reduce((sum, val) => sum + val, 0) / Math.max(1, sleepTimeData.length);
      const avgQuality = qualityData.reduce((sum, val) => sum + val, 0) / Math.max(1, qualityData.length);
      
      const option = {
        tooltip: {
          trigger: 'axis',
          formatter: function(params) {
            let result = params[0].name + '<br/>'
            params.forEach(param => {
              if (param.seriesName === '平均睡眠时长' || param.seriesName === '平均睡眠质量') return;
              let value = param.value
              let unit = param.seriesName === '睡眠时长' ? '小时' : '分'
              result += param.marker + ' ' + param.seriesName + ': ' + value + unit + '<br/>'
            })
            return result
          }
        },
        legend: {
          data: ['睡眠时长', '睡眠质量'],
          textStyle: {
            fontSize: 14
          }
        },
        grid: {
          left: '5%',
          right: '5%',
          bottom: '10%',
          top: '15%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: true,
          data: xAxisData,
          axisLabel: {
            fontSize: 14,
            show: true,
            interval: 0,
            rotate: 0,
            color: '#303133',
            margin: 15,
            formatter: function(value) {
              return value;
            }
          },
          axisTick: {
            alignWithLabel: true,
            show: true,
            length: 6
          },
          axisLine: {
            show: true,
            lineStyle: {
              color: '#909399',
              width: 2
            }
          },
          nameTextStyle: {
            fontSize: 14,
            color: '#303133'
          }
        },
        yAxis: [
          {
            type: 'value',
            name: '时长(小时)',
            min: 0,
            max: 12,
            position: 'left',
            axisLabel: {
              fontSize: 14,
              color: '#83bff6'
            },
            axisLine: {
              show: true,
              lineStyle: {
                color: '#83bff6'
              }
            },
            splitLine: {
              lineStyle: {
                color: '#f0f0f0'
              }
            }
          },
          {
            type: 'value',
            name: '质量(分)',
            min: 0,
            max: 5,
            position: 'right',
            axisLabel: {
              fontSize: 14,
              color: '#FF9900'
            },
            axisLine: {
              show: true,
              lineStyle: {
                color: '#FF9900'
              }
            },
            splitLine: {
              show: false
            }
          }
        ],
        series: [
          {
            name: '睡眠时长',
            type: 'bar',
            data: sleepTimeData,
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: '#83bff6' },
                { offset: 1, color: '#188df0' }
              ])
            },
            emphasis: {
              itemStyle: {
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                  { offset: 0, color: '#2378f7' },
                  { offset: 1, color: '#83bff6' }
                ])
              }
            },
            barWidth: '40%', // 控制柱状图宽度
            showBackground: true, // 显示背景
            backgroundStyle: {
              color: 'rgba(180, 180, 180, 0.1)'
            }
          },
          {
            name: '睡眠质量',
            type: 'line',
            yAxisIndex: 1,
            data: qualityData,
            symbolSize: 10,
            showSymbol: true,
            connectNulls: true,
            symbol: 'circle',
            itemStyle: {
              color: '#FF9900',
              borderWidth: 2,
              borderColor: '#fff'
            },
            lineStyle: {
              width: 4,
              color: '#FF9900'
            },
            emphasis: {
              scale: true,
              focus: 'series',
              itemStyle: {
                borderWidth: 3,
                shadowBlur: 10,
                shadowColor: 'rgba(255, 153, 0, 0.5)'
              }
            }
          }
        ]
      };
      
      this.sleepChart.setOption(option);
    },
    // 格式化日期为后端需要的格式 (YYYY-MM-DD)
    formatDateForBackend(date) {
      if (!date) return '';
      const d = new Date(date);
      const year = d.getFullYear();
      const month = String(d.getMonth() + 1).padStart(2, '0');
      const day = String(d.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    },
    // 格式化时间为后端需要的格式 (HH:MM)
    formatTimeForBackend(time) {
      if (!time) return '';
      const d = new Date(time);
      const hours = String(d.getHours()).padStart(2, '0');
      const minutes = String(d.getMinutes()).padStart(2, '0');
      return `${hours}:${minutes}`;
    },
    // 加载睡眠数据
    loadSleepData() {
      // 初始化状态
      this.hasData = false;
      
      // 加载今日数据
      this.loadTodaySleepData();
      
      // 根据时间范围加载不同数据
      if (this.timeRange === 'week') {
        this.loadWeekSleepData();
        // 加载周睡眠建议
        this.loadWeekSleepAdvice();
      } else if (this.timeRange === 'month') {
        this.loadMonthSleepData();
        // 加载月度睡眠建议
        this.loadMonthSleepAdvice();
      } else if (this.timeRange === 'day') {
        // 加载日睡眠建议
        this.loadDaySleepAdvice();
      }
    },
    // 加载今日睡眠数据
    loadTodaySleepData() {
      const today = this.formatDateForBackend(new Date());
      this.axios.get(`/api/userSleep/getByDate?sleepDate=${today}`)
        .then(response => {
          if (response.data) {
            // 如果有今天的数据，更新表单
            const data = response.data;
            this.sleepForm.date = new Date(data.sleepDate);
            
            // 处理时间字符串转为Date对象
            if (data.sleepTime) {
              const [hours, minutes] = data.sleepTime.split(':');
              const sleepTime = new Date();
              sleepTime.setHours(parseInt(hours, 10), parseInt(minutes, 10), 0);
              this.sleepForm.sleepTime = sleepTime;
            }
            
            if (data.wakeTime) {
              const [hours, minutes] = data.wakeTime.split(':');
              const wakeTime = new Date();
              wakeTime.setHours(parseInt(hours, 10), parseInt(minutes, 10), 0);
              this.sleepForm.wakeTime = wakeTime;
            }
            
            // 确保睡眠质量在0-5之间
            this.sleepForm.quality = this.normalizeSleepQuality(data.sleepQuality) || 3;
            this.sleepForm.feeling = data.sleepFeeling || '';
            this.sleepForm.note = data.remark || '';
            
            // 如果是今日视图，直接显示当天数据而非平均值
            if (this.timeRange === 'day') {
              this.hasData = true;
              // 计算今日睡眠时长
              if (data.sleepTime && data.wakeTime) {
                this.averageSleepTime = this.calculateSleepHours(data.sleepTime, data.wakeTime).toFixed(1);
              } else {
                this.averageSleepTime = '--';
              }
              // 显示今日睡眠质量，确保在0-5之间
              const normalizedQuality = this.normalizeSleepQuality(data.sleepQuality);
              this.averageQuality = normalizedQuality !== null ? normalizedQuality.toFixed(1) : '--';
            }
          } else if (this.timeRange === 'day') {
            // 如果是今日视图且没有数据，则显示无数据
            this.hasData = false;
            this.averageSleepTime = '--';
            this.averageQuality = '--';
          }
        })
        .catch(error => {
          console.error('获取今日睡眠数据失败:', error);
          if (this.timeRange === 'day') {
            this.hasData = false;
            this.averageSleepTime = '--';
            this.averageQuality = '--';
          }
        });
    },
    // 加载周睡眠数据
    loadWeekSleepData() {
      this.axios.get('/api/userSleep/getLastWeek')
        .then(response => {
          if (response.data && response.data.length > 0) {
            // 处理周数据
            const weekData = response.data;
            const xAxisData = [];
            const sleepTimeData = [];
            const qualityData = [];
            
            // 判断返回的数据格式
            const isDetailedFormat = weekData[0].hasOwnProperty('sleepDate');
            const isAggregatedFormat = weekData[0].hasOwnProperty('week_range');
            
            if (isDetailedFormat) {
              // 处理详细的每日睡眠记录格式
              // 获取今天的日期和一周前的日期
              const today = new Date();
              const oneWeekAgo = new Date(today);
              oneWeekAgo.setDate(today.getDate() - 7);
              
              // 创建星期映射表，确保按照周一到周日的顺序显示
              const dayMap = {
                0: '周日', 1: '周一', 2: '周二', 3: '周三', 
                4: '周四', 5: '周五', 6: '周六'
              };
              
              // 初始化一个包含7天的数据结构
              const daysOfWeek = [0, 1, 2, 3, 4, 5, 6].map(day => ({
                day: dayMap[day],
                sleepHours: 0,
                quality: 0,
                hasData: false
              }));
              
              // 计算总睡眠时间和质量，用于平均值
              let totalSleepTime = 0;
              let totalQuality = 0;
              let count = 0;
              let qualityCount = 0;
              
              // 填充实际数据
              weekData.forEach(item => {
                // 提取日期的星期几
                const date = new Date(item.sleepDate);
                
                // 确保数据在过去一周内
                if (date >= oneWeekAgo && date <= today) {
                  const dayIndex = date.getDay(); // 0-6，0表示周日
                
                  // 计算睡眠时长
                  if (item.sleepTime && item.wakeTime) {
                    let sleepHours = this.calculateSleepHours(item.sleepTime, item.wakeTime);
                    daysOfWeek[dayIndex].sleepHours = sleepHours;
                    daysOfWeek[dayIndex].hasData = true;
                    totalSleepTime += sleepHours;
                    count++;
                  }
                
                  // 睡眠质量，确保在0-5之间
                  const normalizedQuality = this.normalizeSleepQuality(item.sleepQuality);
                  if (normalizedQuality !== null) {
                    daysOfWeek[dayIndex].quality = normalizedQuality;
                    daysOfWeek[dayIndex].hasData = true;
                    totalQuality += normalizedQuality;
                    qualityCount++;
                  }
                }
              });
              
              // 按照周一到周日的顺序重新排列
              const orderedDays = [
                daysOfWeek[1], daysOfWeek[2], daysOfWeek[3], 
                daysOfWeek[4], daysOfWeek[5], daysOfWeek[6], daysOfWeek[0]
              ];
              
              // 提取数据到图表数组 - 确保所有七天都显示，无数据的显示为0
              orderedDays.forEach(day => {
                xAxisData.push(day.day);
                sleepTimeData.push(day.sleepHours); // 无数据时为0
                qualityData.push(day.quality); // 无数据时为0
              });
              
              // 确保至少有一条有效数据
              const hasValidData = count > 0 || qualityCount > 0;
              
              // 更新统计数据
              if (hasValidData) {
                this.hasData = true; // 设置有数据标记
                this.averageSleepTime = count > 0 ? (totalSleepTime / count).toFixed(1) : '0.0';
                this.averageQuality = qualityCount > 0 ? (totalQuality / qualityCount).toFixed(1) : '0.0';
                
                // 计算最佳睡眠时间
                this.calculateBestSleepTime(weekData);
                
                this.noChartData = false;
                
                // 更新图表
                this.$nextTick(() => {
                  this.updateChartWithData(xAxisData, sleepTimeData, qualityData);
                });
              } else {
                this.hasData = false;
                this.noChartData = true;
              }
            } else if (isAggregatedFormat) {
              // 处理聚合的周数据格式
              // 计算总睡眠时间和质量，用于平均值
              let totalSleepTime = 0;
              let totalQuality = 0;
              let totalDays = 0;
              let dataCount = 0;
              
              // 填充实际数据
              weekData.forEach(item => {
                // 从周范围提取日期作为x轴标签
                const weekRange = item.week_range;
                xAxisData.push(weekRange);
                
                // 计算平均睡眠时长
                const sleepDays = parseFloat(item.sleep_days || 0);
                const totalHours = parseFloat(item.total_sleep_hours || 0);
                const avgSleepHours = sleepDays > 0 ? totalHours / sleepDays : 0;
                sleepTimeData.push(avgSleepHours);
                
                // 处理睡眠质量
                const qualityScore = parseFloat(item.avg_sleep_quality_score || 0);
                const normalizedQuality = this.normalizeSleepQuality(qualityScore);
                qualityData.push(normalizedQuality);
                
                // 累计总值用于计算平均值
                if (sleepDays > 0) {
                  totalSleepTime += totalHours; // 累加总小时数而非平均值
                  totalDays += sleepDays;
                }
                
                if (normalizedQuality > 0) {
                  totalQuality += normalizedQuality;
                  dataCount++;
                }
              });
              
              // 确保至少有一条有效数据
              const hasValidData = totalDays > 0 || dataCount > 0;
              
              // 更新统计数据
              if (hasValidData) {
                this.hasData = true; // 设置有数据标记
                // 正确计算平均睡眠时长：总小时数除以总天数
                this.averageSleepTime = totalDays > 0 ? (totalSleepTime / totalDays).toFixed(1) : '0.0';
                // 正确计算平均睡眠质量
                this.averageQuality = dataCount > 0 ? (totalQuality / dataCount).toFixed(1) : '0.0';
                
                // 设置最佳睡眠时间 - 对于聚合数据，可能无法确定具体时间
                this.bestSleepTime = '--';
                
                this.noChartData = false;
                
                // 更新图表
                this.$nextTick(() => {
                  this.updateChartWithData(xAxisData, sleepTimeData, qualityData);
                });
              } else {
                this.hasData = false;
                this.noChartData = true;
              }
            } else {
              // 未知数据格式
              this.hasData = false;
              this.noChartData = true;
              console.error('未知的数据格式:', weekData[0]);
            }
          } else {
            this.hasData = false;
            this.noChartData = true;
          }
        })
        .catch(error => {
          console.error('获取周睡眠数据失败:', error);
          this.hasData = false;
          this.noChartData = true;
        });
    },
    // 加载月睡眠数据
    loadMonthSleepData() {
      this.axios.get('/api/userSleep/getByWeekInMonth')
        .then(response => {
          if (response.data && response.data.length > 0) {
            // 处理月数据
            const monthData = response.data;
            
            // 检查是否有第五周数据
            let hasFifthWeek = false;
            
            // 遍历数据检查是否有第五周
            for (const item of monthData) {
              if (item && item.week_range) {
                const startDate = item.week_range.split(' ~ ')[0];
                const weekNumber = this.getWeekNumberInMonth(startDate);
                if (weekNumber === 5) {
                  hasFifthWeek = true;
                  break;
                }
              }
            }
            
            // 根据是否有第五周动态设置x轴数据和初始数据数组
            const xAxisData = hasFifthWeek ? 
              ['第1周', '第2周', '第3周', '第4周', '第5周'] : 
              ['第1周', '第2周', '第3周', '第4周'];
              
            const sleepTimeData = hasFifthWeek ? [0, 0, 0, 0, 0] : [0, 0, 0, 0]; // 初始化为0
            const qualityData = hasFifthWeek ? [0, 0, 0, 0, 0] : [0, 0, 0, 0]; // 初始化为0
            
            // 计算总睡眠时间和质量，用于平均值
            let totalSleepTime = 0;
            let totalQuality = 0;
            let qualityCount = 0;
            let totalDays = 0;
            
            // 创建一个映射来存储周数据
            const weekDataMap = {
              1: null, 2: null, 3: null, 4: null, 5: null
            };
            
            // 处理每周数据
            monthData.forEach((item) => {
              // 确保有有效的数据
              if (item && item.week_range && item.sleep_days > 0) {
                // 从周范围中提取开始日期
                const weekRange = item.week_range;
                const startDate = weekRange.split(' ~ ')[0];
                const weekNumber = this.getWeekNumberInMonth(startDate);
                
                // 处理睡眠时长 - 使用total_sleep_hours除以sleep_days获取平均值
                const sleepDays = parseFloat(item.sleep_days || 0);
                const totalHours = parseFloat(item.total_sleep_hours || 0);
                const avgSleepHours = sleepDays > 0 ? totalHours / sleepDays : 0;
              
                // 处理睡眠质量 - 使用avg_sleep_quality_score
                const qualityScore = parseFloat(item.avg_sleep_quality_score || 0);
                const normalizedQuality = this.normalizeSleepQuality(qualityScore);
                
                // 将数据存储到对应周位置
                if (weekNumber >= 1 && weekNumber <= 5) {
                  weekDataMap[weekNumber] = {
                    weekRange,
                    weekNumber,
                    avgSleepHours,
                    avgQuality: normalizedQuality,
                    sleepDays,
                    totalHours
                  };
                  
                  // 更新图表数据数组
                  if (weekNumber <= sleepTimeData.length) {
                    sleepTimeData[weekNumber - 1] = avgSleepHours;
                    qualityData[weekNumber - 1] = normalizedQuality;
                  }
                  
                  // 累计总值用于计算平均值
                  if (sleepDays > 0) {
                    totalSleepTime += totalHours;
                    totalDays += sleepDays;
                  }
                  
                  if (normalizedQuality > 0) {
                    totalQuality += normalizedQuality;
                    qualityCount++;
                  }
                }
              }
            });
            
            // 检查是否有任何有效数据
            const hasAnyData = Object.values(weekDataMap).some(week => week !== null);
            
            // 更新统计数据
            if (hasAnyData) {
              this.hasData = true; // 设置有数据标记
              
              // 正确计算平均睡眠时长：总小时数除以总天数
              this.averageSleepTime = totalDays > 0 ? (totalSleepTime / totalDays).toFixed(1) : '0.0';
              
              // 正确计算平均睡眠质量：总质量分数除以有质量数据的周数
              this.averageQuality = qualityCount > 0 ? (totalQuality / qualityCount).toFixed(1) : '0.0';
              
              // 尝试获取最佳睡眠时间
              this.axios.get('/api/userSleep/getLastWeek')
                .then(weekResponse => {
                  if (weekResponse.data && weekResponse.data.length > 0) {
                    this.calculateBestSleepTime(weekResponse.data);
                  }
                })
                .catch(err => console.error('获取周数据失败:', err));
              
              this.noChartData = false;
              
              // 更新图表
              this.$nextTick(() => {
                this.updateChartWithData(xAxisData, sleepTimeData, qualityData);
              });
            } else {
              this.hasData = false;
              this.noChartData = true;
            }
          } else {
            this.hasData = false;
            this.noChartData = true;
          }
        })
        .catch(error => {
          console.error('获取月睡眠数据失败:', error);
          this.hasData = false;
          this.noChartData = true;
        });
    },
    // 计算睡眠时长（小时）
    calculateSleepHours(sleepTime, wakeTime) {
      // 解析时间字符串
      const [sleepHours, sleepMinutes] = sleepTime.split(':').map(Number);
      const [wakeHours, wakeMinutes] = wakeTime.split(':').map(Number);
      
      // 转换为分钟计算
      let sleepTotalMinutes = sleepHours * 60 + sleepMinutes;
      let wakeTotalMinutes = wakeHours * 60 + wakeMinutes;
      
      // 处理跨天情况
      if (wakeTotalMinutes < sleepTotalMinutes) {
        wakeTotalMinutes += 24 * 60; // 加一天
      }
      
      // 计算差值并转换为小时
      const durationMinutes = wakeTotalMinutes - sleepTotalMinutes;
      return parseFloat((durationMinutes / 60).toFixed(1));
    },
    calculateBestSleepTime(data) {
      if (!data || data.length === 0) {
        this.bestSleepTime = '--';
        return;
      }
      
      try {
        // 找出质量评分最高的睡眠记录
        let bestRecord = null;
        let highestQuality = -1;
        
        data.forEach(record => {
          const quality = this.normalizeSleepQuality(record.sleepQuality);
          if (quality !== null && quality > highestQuality) {
            highestQuality = quality;
            bestRecord = record;
          }
        });
        
        if (bestRecord && bestRecord.sleepTime) {
          // 提取最佳入睡时间的小时部分
          const hourMatch = bestRecord.sleepTime.match(/^(\d{1,2}):/);
          if (hourMatch && hourMatch[1]) {
            this.bestSleepTime = hourMatch[1];
          } else {
            this.bestSleepTime = '--';
          }
        } else {
          this.bestSleepTime = '--';
        }
      } catch (error) {
        console.error('计算最佳睡眠时间失败:', error);
        this.bestSleepTime = '--';
      }
    },
    // 添加一个方法来规范化睡眠质量，确保其值在0-5之间
    normalizeSleepQuality(quality) {
      if (quality === null || quality === undefined) return null;
      
      // 处理文本类型的睡眠质量
      if (typeof quality === 'string') {
        switch (quality) {
          case '很差': return 1;
          case '较差': return 2;
          case '一般': return 3;
          case '良好': return 4;
          case '优秀': return 5;
          case '精力充沛': return 5;
          case '疲惫': return 2;
          default:
            // 尝试将字符串转为数字
            const numValue = parseFloat(quality);
            if (!isNaN(numValue)) {
              return this.normalizeSleepQuality(numValue);
            }
            return 3; // 默认中等质量
        }
      }
      
      // 如果质量值大于5，可能是百分比形式，需要转换
      if (quality > 5) {
        // 假设是百分比形式（0-100），转换为0-5
        return Math.min(5, Math.max(0, quality / 20));
      }
      
      // 确保值在0-5之间
      return Math.min(5, Math.max(0, quality));
    },
    getWeekNumberInMonth(dateStr) {
      const date = new Date(dateStr);
      const year = date.getFullYear();
      const month = date.getMonth() + 1;
      const firstDay = new Date(year, month - 1, 1).getDay();
      const day = date.getDate();
      const weekNumber = Math.ceil((day + firstDay) / 7);
      return weekNumber;
    },
    // 添加加载月度睡眠建议的方法
    loadMonthSleepAdvice() {
      this.axios.get('/api/api/health/sleep/advice/month')
        .then(response => {
          if (response.data) {
            this.monthAdvice = response.data;
          } else {
            this.monthAdvice = '';
          }
        })
        .catch(error => {
          console.error('获取月度睡眠建议失败:', error);
          this.monthAdvice = '';
        });
    },
    
    // 添加加载周睡眠建议的方法
    loadWeekSleepAdvice() {
      this.axios.get('/api/api/health/sleep/advice/week')
        .then(response => {
          if (response.data) {
            this.weekAdvice = response.data;
          } else {
            this.weekAdvice = '';
          }
        })
        .catch(error => {
          console.error('获取周睡眠建议失败:', error);
          this.weekAdvice = '';
        });
    },
    
    // 添加加载日睡眠建议的方法
    loadDaySleepAdvice() {
      const today = this.formatDateForBackend(new Date());
      this.axios.get(`/api/api/health/sleep/advice/day?date=${today}`)
        .then(response => {
          if (response.data) {
            this.dayAdvice = response.data;
          } else {
            this.dayAdvice = '';
          }
        })
        .catch(error => {
          console.error('获取日睡眠建议失败:', error);
          this.dayAdvice = '';
        });
    },
    
    // 格式化睡眠建议显示
    formatAdvice(text) {
      if (!text) return '';
      
      // 1. 先规范化中文字符的序号格式
      // 处理一、二、三这样的中文序号，统一添加样式
      text = text.replace(/^(一|二|三|四|五|六|七|八|九|十)、\s*(.*?)$/gm, 
        '<h3 class="advice-section-title chinese-number"><span class="section-number">$1、</span>$2</h3>');
      
      // 处理1、2、3这样的数字序号加顿号的标题
      text = text.replace(/^(\d+)、\s*(.*?)$/gm,
        '<h3 class="advice-section-title number-title"><span class="section-number">$1、</span>$2</h3>');
      
      // 2. 处理标题行中的特殊图标
      text = text.replace(/🔍\s*(数据分析.*?:|数据异常警示:?)/g, 
        '<h3 class="advice-section-title"><i class="el-icon-data-analysis"></i> $1</h3>');
      text = text.replace(/✏️\s*(改善建议.*?:|现有问题分析:?)/g, 
        '<h3 class="advice-section-title"><i class="el-icon-edit-outline"></i> $1</h3>');
      
      // 3. 处理数字列表（不带顿号的常规数字列表）
      text = text.replace(/^(\d+)\.\s+(.*?)$/gm, 
        '<div class="advice-item-number"><span class="number">$1.</span> <span class="content">$2</span></div>');
      
      // 4. 处理特殊的角标列表
      text = text.replace(/^[▶▷➤➢►]\s+(.*?)$/gm, 
        '<div class="advice-item-arrow"><i class="el-icon-arrow-right"></i> <span class="content">$1</span></div>');
      
      // 5. 处理破折号列表
      text = text.replace(/^-\s+(.*?)$/gm, 
        '<div class="advice-item-dash"><i class="el-icon-minus"></i> <span class="content">$1</span></div>');
      
      // 6. 处理缩进的右箭头列表
      text = text.replace(/^\s*[>→➔]\s+(.*?)$/gm, 
        '<div class="advice-item-indented"><i class="el-icon-d-arrow-right"></i> <span class="content">$1</span></div>');
      
      // 7. 处理强调内容
      text = text.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>');
      
      // 8. 处理特殊符号和标识
      text = text.replace(/🔍/g, '<i class="el-icon-search advice-icon"></i>');
      text = text.replace(/✅/g, '<i class="el-icon-check advice-icon success"></i>');
      text = text.replace(/🌙/g, '<i class="el-icon-moon advice-icon"></i>');
      text = text.replace(/📊/g, '<i class="el-icon-data-line advice-icon"></i>');
      text = text.replace(/✏️/g, '<i class="el-icon-edit advice-icon"></i>');
      
      // 9. 处理时间范围和日期
      text = text.replace(/(\d{1,2}\.\d{1,2}-\d{1,2}\.\d{1,2})/g, '<span class="date-range">$1</span>');
      
      // 10. 处理换行
      text = text.replace(/\n/g, '<br>');
      
      return text;
    }
  },
  beforeDestroy() {
    // 移除窗口大小变化监听
    window.removeEventListener('resize', this.handleResize);
    
    // 组件销毁前释放echarts实例
    if (this.sleepChart) {
      this.sleepChart.dispose()
      this.sleepChart = null
    }
  }
}
</script>

<style>
/* 添加全局样式，确保没有任何边距 */
html, body {
  margin: 0 !important;
  padding: 0 !important;
  overflow-x: hidden;
  width: 100vw;
  max-width: 100vw;
}
</style>

<style scoped>
.sleep-container {
  padding: 0;
  margin: 0;
  background: linear-gradient(120deg, #e0c3fc 0%, #8ec5fc 100%);
  min-height: 100vh;
  height: 100%;
  width: 100%;
  overflow-x: hidden;
  box-sizing: border-box;
  position: relative;
  display: flex;
  flex-direction: column;
}

.main-content {
  display: flex;
  gap: 30px;
  width: 100%;
  padding: 20px;
  box-sizing: border-box;
  flex: 1;
}

.record-form {
  flex: 0 0 28%;
  min-width: 320px;
  max-width: 420px;
  background: rgba(255,255,255,0.95);
  border-radius: 15px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.05);
  transition: box-shadow 0.3s ease;
}

.record-form:hover {
  box-shadow: 0 8px 30px rgba(0, 0, 0, 0.1);
}

.analysis-section {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 25px;
}

.time-range {
  background: rgba(255,255,255,0.95);
  border-radius: 15px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.05);
  padding: 15px;
  text-align: center;
  height: 80px; /* 固定高度 */
  display: flex;
  align-items: center;
  justify-content: center;
}

:deep(.el-radio-group) {
  display: flex;
  justify-content: center;
  width: 100%;
  height: 50px; /* 固定高度 */
}

:deep(.el-radio-button) {
  height: 50px;
  width: 120px; /* 固定宽度 */
}

:deep(.el-radio-button__inner) {
  font-size: 18px;
  padding: 0;
  height: 50px;
  line-height: 50px;
  width: 100%;
  border-radius: 8px;
  margin: 0 5px;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  justify-content: center;
}

:deep(.el-radio-button__inner:hover) {
  background-color: #ecf5ff;
  color: #409EFF;
}

:deep(.el-radio-button__original-radio:checked + .el-radio-button__inner) {
  background-color: #409EFF;
  border-color: #409EFF;
  box-shadow: 0 2px 10px rgba(64, 158, 255, 0.3);
}

.sleep-stats {
  background: rgba(255,255,255,0.95);
  border-radius: 15px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.05);
  transition: box-shadow 0.3s ease;
  min-height: 200px; /* 设置最小高度 */
  overflow: hidden; /* 防止内容溢出 */
}

.sleep-stats:hover {
  box-shadow: 0 8px 30px rgba(0, 0, 0, 0.1);
}

.stats-content {
  display: flex;
  justify-content: space-around;
  text-align: center;
  padding: 20px 0;
  min-height: 120px; /* 设置最小高度 */
}

.stat-item {
  padding: 15px 10px; /* 调整内边距 */
  width: 33.33%; /* 确保均匀分布 */
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  box-sizing: border-box; /* 确保padding不影响宽度计算 */
}

.value-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 90px; /* 固定高度 */
  width: 100%; /* 确保宽度100% */
}

.stat-item h3 {
  font-size: 18px;
  color: #606266;
  margin-bottom: 10px;
  margin-top: 0;
  text-align: center;
  width: 100%;
  white-space: nowrap; /* 防止标题换行 */
  overflow: hidden; /* 防止溢出 */
  text-overflow: ellipsis; /* 文字溢出时显示省略号 */
}

.stat-item .number {
  font-size: 36px; /* 减小字体以适应更多数字 */
  background: linear-gradient(45deg, #409EFF, #67C23A);
  -webkit-background-clip: text;
  background-clip: text;
  color: transparent;
  font-weight: bold;
  margin: 0;
  line-height: 1.2;
  text-align: center;
  width: 100%;
  white-space: nowrap; /* 防止数字换行 */
  overflow: hidden; /* 防止溢出 */
  text-overflow: ellipsis; /* 文字溢出时显示省略号 */
}

.stat-item .unit {
  font-size: 16px;
  color: #909399;
  margin: 5px 0 0;
  text-align: center;
  width: 100%;
  white-space: nowrap; /* 防止单位换行 */
}

.stat-item:hover {
  transform: none;
}

/* 图表容器样式 */
.charts-container {
  height: 520px; /* 固定高度 */
  position: relative;
  margin-bottom: 25px;
  display: block;
  transition: all 0.3s ease; /* 添加过渡效果 */
  overflow: hidden; /* 防止内容溢出 */
}

/* 添加淡入淡出动画 */
.fade-enter-active, .fade-leave-active {
  transition: opacity 0.3s, transform 0.3s;
}
.fade-enter, .fade-leave-to {
  opacity: 0;
  transform: translateY(10px); /* 添加轻微的上移效果 */
}

.sleep-trend {
  background: rgba(255,255,255,0.95);
  border-radius: 15px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
  display: flex;
  flex-direction: column;
  height: 100%; /* 使用100%高度填充容器 */
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  width: 100%;
  z-index: 1;
}

.sleep-trend:hover {
  box-shadow: 0 8px 30px rgba(0, 0, 0, 0.1);
}

.chart-container {
  height: 450px;
  padding: 20px;
  width: 100%;
  flex-grow: 1;
  position: relative;
}

/* 图表加载状态样式 */
.chart-loading, .chart-empty {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background-color: rgba(255, 255, 255, 0.8);
}

.chart-loading i, .chart-empty i {
  font-size: 48px;
  color: #409EFF;
  margin-bottom: 15px;
}

.chart-loading p, .chart-empty p {
  font-size: 18px;
  color: #606266;
  margin: 0;
}

.sleep-advice {
  background: rgba(255,255,255,0.95);
  border-radius: 15px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.05);
  transition: box-shadow 0.3s ease;
  min-height: 280px;
}

.sleep-advice:hover {
  box-shadow: 0 8px 30px rgba(0, 0, 0, 0.1);
}

.advice-content {
  padding: 20px;
}

.advice-item {
  display: flex;
  align-items: flex-start;
  gap: 15px;
  margin-bottom: 20px;
  padding: 15px;
  border-radius: 10px;
  background: #f8f9fa;
  transition: all 0.3s ease;
}

.advice-item:hover {
  background: #ecf5ff;
  transform: translateX(5px);
}

.advice-item i {
  font-size: 24px;
  color: #409EFF;
  margin-top: 2px;
}

.advice-item p {
  margin: 0;
  line-height: 1.8;
  color: #606266;
  font-size: 16px;
}

:deep(.el-card__header) {
  font-size: 20px;
  font-weight: bold;
  color: #303133;
  padding: 20px;
  border-bottom: 1px solid #ebeef5;
}

:deep(.el-form-item__label) {
  float: left !important;
  display: inline-block !important;
  text-align: right !important;
  font-size: 16px;
  color: #606266;
}

:deep(.el-form-item__content) {
  margin-left: 120px !important;
  clear: none !important;
}

:deep(.el-rate) {
  display: inline-flex !important;
  margin-top: 0 !important;
  height: auto !important; /* 改为auto以适应内容 */
  line-height: normal !important; /* 使用normal以避免行高问题 */
  vertical-align: middle !important;
  padding-left: 0 !important; /* 确保没有左内边距 */
}

/* 特殊处理睡眠质量的星级评分 */
.el-form-item.is-required:not(.is-no-asterisk) > .el-form-item__label[for="quality"]:before,
.el-form-item.is-required:not(.is-no-asterisk) > .el-form-item__label:before {
  content: "* ";
  color: #F56C6C;
  margin-right: 4px;
}

/* 调整星级评分的样式 */
:deep(.el-rate__icon) {
  margin-right: 8px !important; /* 调整星星之间的间距 */
  font-size: 20px !important; /* 保持较小的星星大小 */
  vertical-align: middle !important;
}

:deep(.el-input__inner),
:deep(.el-textarea__inner) {
  font-size: 16px;
  border-radius: 8px;
  border: 1px solid #dcdfe6;
  transition: all 0.3s ease;
}

:deep(.el-input__inner:focus),
:deep(.el-textarea__inner:focus) {
  border-color: #409EFF;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

:deep(.el-button) {
  font-size: 16px;
  padding: 12px 25px;
  border-radius: 8px;
  transition: all 0.3s ease;
}

:deep(.el-button--primary) {
  background: linear-gradient(45deg, #409EFF, #67C23A);
  border: none;
}

:deep(.el-button--primary:hover) {
  transform: translateY(-2px);
  box-shadow: 0 4px 15px rgba(64, 158, 255, 0.3);
}

:deep(.el-collapse-item__header) {
  font-size: 18px;
  color: #303133;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 8px;
  transition: all 0.3s ease;
}

:deep(.el-collapse-item__header:hover) {
  background: #ecf5ff;
  color: #409EFF;
}

:deep(.el-collapse-item__content) {
  padding: 20px;
}

:deep(.el-date-editor.el-input),
:deep(.el-date-editor.el-input__inner) {
  width: 100%;
}

:deep(.el-select .el-input__inner) {
  height: 40px;
  line-height: 40px;
}

/* 添加响应式布局 */
@media screen and (max-width: 1200px) {
  .main-content {
    flex-direction: column;
    padding: 15px;
    gap: 20px;
  }
  
  .record-form {
    width: 100%;
    max-width: none;
    margin-bottom: 20px;
  }
  
  .stats-content {
    flex-wrap: wrap;
  }
  
  .stat-item {
    width: 100%;
    padding: 10px;
  }
  
  .charts-container {
    height: 400px;
  }
  
  .sleep-trend {
    height: 400px;
  }
  
  .chart-container {
    height: 330px;
  }
}

@media screen and (max-width: 768px) {
  .sleep-container {
    padding: 0;
  }
  
  .main-content {
    padding: 10px;
  }
  
  :deep(.el-radio-button) {
    height: 40px;
    width: 90px;
  }
  
  :deep(.el-radio-button__inner) {
    height: 40px;
    line-height: 40px;
    font-size: 16px;
  }
  
  .sleep-stats {
    min-height: 180px;
  }
  
  .stats-content {
    min-height: 100px;
    padding: 10px 0;
  }
  
  .stat-item .number {
    font-size: 36px;
  }
  
  .stat-item .unit {
    font-size: 14px;
  }
  
  .stat-item h3 {
    font-size: 16px;
  }
  
  .value-container {
    height: 70px;
  }
  
  .charts-container {
    height: 350px;
  }
  
  .sleep-trend {
    height: 350px;
  }
  
  .chart-container {
    height: 290px;
    padding: 10px;
  }
}

/* 特殊处理睡眠质量表单项 */
.quality-form-item {
  margin-bottom: 22px !important; /* 调整底部间距 */
}

.quality-form-item :deep(.el-form-item__content) {
  display: flex !important;
  align-items: center !important;
  height: 40px !important;
  margin-left: 120px !important; /* 与其他表单项一致的左边距 */
}

.quality-form-item :deep(.el-rate) {
  margin-left: 0 !important; /* 与输入框左侧对齐 */
  padding: 0 !important; /* 移除所有内边距 */
  line-height: normal !important;
  display: flex !important;
  align-items: center !important;
}

.stat-item .no-data {
  font-size: 20px;
  color: #909399;
  margin: 0;
  text-align: center;
  width: 100%;
  font-style: italic;
}

/* 月度建议样式 */
.month-advice {
  padding: 10px;
}

.month-advice-content {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 20px;
  transition: all 0.3s ease;
  text-align: left;
}

.month-advice-content:hover {
  background: #ecf5ff;
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.1);
}

/* 周建议样式 */
.week-advice {
  padding: 10px;
}

.week-advice-content {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 20px;
  transition: all 0.3s ease;
  text-align: left;
}

.week-advice-content:hover {
  background: #ecf5ff;
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.1);
}

/* 日建议样式 */
.day-advice {
  padding: 10px;
}

.day-advice-content {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 20px;
  transition: all 0.3s ease;
  text-align: left;
}

.day-advice-content:hover {
  background: #ecf5ff;
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.1);
}

.no-data-advice {
  padding: 10px;
}

/* 替换旧的pre样式，改为格式化建议的样式 */
.formatted-advice {
  font-size: 16px;
  line-height: 1.8;
  color: #606266;
  text-align: left;
}

/* 章节标题样式 */
.advice-section-title {
  font-size: 20px;
  color: #409EFF;
  margin: 25px 0 15px 0;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
  display: flex;
  align-items: center;
}

.advice-section-title:first-child {
  margin-top: 0;
}

.advice-section-title i {
  margin-right: 8px;
  font-size: 22px;
}

/* 中文序号样式 */
.advice-section-title.chinese-number {
  color: #303133;
  font-weight: bold;
}

/* 数字序号样式 */
.advice-section-title.number-title {
  color: #303133;
  font-weight: bold;
}

.section-number {
  margin-right: 8px;
  color: #409EFF;
  font-weight: bold;
}

/* 列表项样式 */
.advice-item-number {
  margin: 12px 0;
  display: flex;
  align-items: flex-start;
}

.advice-item-number .number {
  font-weight: bold;
  color: #409EFF;
  margin-right: 8px;
  flex-shrink: 0;
  min-width: 20px;
}

.advice-item-number .content {
  flex: 1;
}

.advice-item-dash {
  margin: 8px 0 8px 20px;
  display: flex;
  align-items: flex-start;
}

.advice-item-dash i {
  color: #67C23A;
  margin-right: 8px;
  flex-shrink: 0;
}

.advice-item-dash .content {
  flex: 1;
}

/* 新增箭头列表样式 */
.advice-item-arrow {
  margin: 12px 0;
  display: flex;
  align-items: flex-start;
}

.advice-item-arrow i {
  color: #E6A23C;
  margin-right: 8px;
  flex-shrink: 0;
}

.advice-item-arrow .content {
  flex: 1;
}

/* 缩进列表样式 */
.advice-item-indented {
  margin: 8px 0 8px 30px;
  display: flex;
  align-items: flex-start;
}

.advice-item-indented i {
  color: #F56C6C;
  margin-right: 8px;
  flex-shrink: 0;
}

.advice-item-indented .content {
  flex: 1;
}

/* 日期范围 */
.date-range {
  background-color: #f0f9eb;
  color: #67C23A;
  padding: 2px 6px;
  border-radius: 4px;
  font-weight: bold;
}

.formatted-advice strong {
  color: #E6A23C;
  font-weight: bold;
}

.advice-icon {
  font-size: 18px;
  vertical-align: middle;
  margin: 0 4px;
}

.advice-icon.success {
  color: #67C23A;
}

.loading-advice {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px 0;
}

.loading-advice i {
  font-size: 36px;
  color: #409EFF;
  margin-bottom: 15px;
}

.loading-advice p {
  font-size: 16px;
  color: #909399;
  margin: 0;
}
</style>
